// ==================================================================
// 描 述：
// 作 者：王征:D
// 创建时间：2019/05/30 14:00:37
// ==============================================================
using ProtoBuf.Message;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Yunchang;
using Yunchang.NetworkLayer;
using Table.Blo;
using Table.DataModel;

namespace AutoChess
{
    partial class AutoChessManager
    {
        private CommonEffect _floorSelectEff = null;
        private CommonEffect _floorSelectEffBig = null;
        private CommonEffect _floorHighLightEff = null;
        private CommonEffect _floorHighLightEffBig = null;
        private CommonEffect _squreEff = null;
        private bool _inBattleFiled = false;

        //private object[] _shopRarityEff = new object[5];
        //private Dictionary<int, object> _sameChessEff = new Dictionary<int, object>();

        private List<CommonEffect> _sameBuffEffect = new List<CommonEffect>();

        private GameObject arrowObj;

        public void ClearAllEffect()
        {
            if (_floorSelectEff != null)
            {
                _floorSelectEff.Clear();
                _floorSelectEff = null;
            }
            if (_floorHighLightEff != null)
            {
                _floorHighLightEff.Clear();
                _floorHighLightEff = null;
            }
            if (_floorSelectEffBig != null)
            {
                _floorSelectEffBig.Clear();
                _floorSelectEffBig = null;
            }
            if (_floorHighLightEffBig != null)
            {
                _floorHighLightEffBig.Clear();
                _floorHighLightEffBig = null;
            }
            if (_squreEff != null)
            {
                _squreEff.Clear();
                _squreEff = null;
            }
            foreach (var item in _sameBuffEffect)
            {
                item.Clear();
            }
            _sameBuffEffect.Clear();
            if (arrowObj != null)
            {
                UnityEngine.GameObject.Destroy(arrowObj);
                arrowObj = null;
            }
            _inBattleFiled = false;
        }

        public void InitArrowMesh(Transform tsm)
        {
            arrowObj = CustomMeshBuilder.CreateArcMesh("Arrow", AutoChessFieldViewCtr.Ins.SceneConfig.arrowMeshMat, new CustomMeshArgs(Vector3.zero, Vector3.zero, 1, 2));
            arrowObj.transform.SetParent(tsm);
            arrowObj.SetActive(false);
            _inBattleFiled = true;
        }

        public void ChangeMeshPos(bool active, Vector3 ori, Vector3 tar)
        {
            if (!active)
            {
                arrowObj.SetActive(false);
            }
            else
            {
                arrowObj.SetActive(true);
                CustomMeshBuilder.UpdateMesh(arrowObj, new CustomMeshArgs(ori, tar, 1, 2));
            }
        }

        /// <summary>
        /// 处理地板选中特效
        ///  -位置移动
        ///  -显隐控制
        /// </summary>
        /// <param name="gridUnit"></param>
        public void SetFloorEffectSelect(bool active, ACGrid gridUnit = null)
        {
            if (active)
            {
                if (_floorSelectEff == null)
                {
                    _floorSelectEff = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Grid_Frame, gridUnit.Display.transform);
                }
                if (_floorSelectEffBig == null)
                {
                    _floorSelectEffBig = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_150_zizhouqi_xiaokuai01, gridUnit.Display.transform);
                }
            }

            CommonEffect current = null;
            CommonEffect notUsed = null;
            if (gridUnit != null && gridUnit.GridType == GridType.PreChooseGrid)
            {
                current = _floorSelectEff;
                notUsed = _floorSelectEffBig;
            }
            else
            {
                current = _floorSelectEffBig;
                notUsed = _floorSelectEff;
            }

            if (active)
            {
                current.GetEffectHolder().SetParent(gridUnit.Display.transform, false);
                current.GetEffectHolder().gameObject.SetActive(true);
                notUsed.GetEffectHolder().gameObject.SetActive(false);
            }
            else
            {
                if (current != null)
                    current.GetEffectHolder().gameObject.SetActive(false);
                if (notUsed != null)
                    notUsed.GetEffectHolder().gameObject.SetActive(false);
            }
        }

        /// <summary>
        /// 处理地板选中高亮特效
        ///  -位置移动
        ///  -显隐控制
        /// </summary>
        /// <param name="gridUnit"></param>
        public void SetFloorEffectHighLight(bool active, ACGrid gridUnit = null)
        {
            if (active)
            {
                if (_floorHighLightEff == null)
                {
                    _floorHighLightEff = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Grid_Frame, gridUnit.Display.transform);
                }
                if (_floorHighLightEffBig == null)
                {
                    _floorHighLightEffBig = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_150_zizhouqi_xiaokuai01, gridUnit.Display.transform);
                }
            }

            CommonEffect current = null;
            CommonEffect notUsed = null;
            if (gridUnit != null && gridUnit.GridType == GridType.PreChooseGrid)
            {
                current = _floorHighLightEff;
                notUsed = _floorHighLightEffBig;
            }
            else
            {
                current = _floorHighLightEffBig;
                notUsed = _floorHighLightEff;
            }

            if (active)
            {
                current.GetEffectHolder().SetParent(gridUnit.Display.transform, false);
                current.GetEffectHolder().gameObject.SetActive(true);
                notUsed.GetEffectHolder().gameObject.SetActive(false);
            }
            else
            {
                if (current != null)
                    current.GetEffectHolder().gameObject.SetActive(false);
                if (notUsed != null)
                    notUsed.GetEffectHolder().gameObject.SetActive(false);
            }
        }

        public void SetSqureEffect(bool active)
        {
            if (active)
            {
                if (_squreEff == null)
                {
                    _squreEff = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Field_Frame, AutoChessFieldViewCtr.Ins.SceneEffectRoot, (gameObj) =>
                    {
                        gameObj.transform.localPosition = new Vector3(-5.33f, 0.2f, 1.88f);
                    });
                }
                _squreEff.GetEffectHolder().gameObject.SetActive(true);
            }
            else
            {
                if (_squreEff != null)
                {
                    _squreEff.GetEffectHolder().gameObject.SetActive(false);
                }
            }
        }

        public void SetSameBuffEffect(bool active, int acHeroGroup = 0)
        {
            if (active && _inBattleFiled)
            {
                List<ACGrid> buffGrids = new List<ACGrid>();
                HashSet<int> validHero = new HashSet<int>();
                foreach (var unit in AutoChessPlayerCtr.Ins.CurrentPlayer.HeroUnits)
                {
                    if (unit.MapGrid.GridType != GridType.FightGrid)
                        continue;

                    if (validHero.Contains(unit.HeroID))
                    {
                        buffGrids.Add(unit.MapGrid);
                        continue;
                    }

                    var tableChess = AutoChessBlo.GetChessHero(unit.HeroID);
                    var groups = tableChess.acHeroGroups.Split(';');
                    foreach (var item in groups)
                    {
                        var group = int.Parse(item);
                        if (group == acHeroGroup)
                        {
                            buffGrids.Add(unit.MapGrid);
                            validHero.Add(unit.HeroID);
                            break;
                        }
                    }
                }
                int i = 0;
                for (; i < buffGrids.Count; i++)
                {
                    if (i >= _sameBuffEffect.Count)
                    {
                        var targetTsm = buffGrids[i].Display.transform;
                        var eff = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Hero_Same_Buff, targetTsm);
                        _sameBuffEffect.Add(eff);
                    }
                    else
                    {
                        _sameBuffEffect[i].GetEffectHolder().SetParent(buffGrids[i].Display.transform, false);
                        _sameBuffEffect[i].GetEffectHolder().gameObject.SetActive(true);
                    }
                }
                for (; i < _sameBuffEffect.Count; i++)
                {
                    _sameBuffEffect[i].GetEffectHolder().gameObject.SetActive(false);
                }
            }
            else
            {
                for (int i = 0; i < _sameBuffEffect.Count; i++)
                {
                    _sameBuffEffect[i].Clear();
                }
                _sameBuffEffect.Clear();
            }
        }

        // 一次性特效
        public void ShotStarUpgradeEffect(ACGrid gridUnit)
        {
            CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Hero_Star_Up, gridUnit.Display.transform);
        }

        public void ShotAppearEffect(ACGrid gridUnit)
        {
            CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_150_zizhouqi_renwu_xialuo, gridUnit.Display.transform);
        }

        public void ShotSellChessEffect(ACGrid gridUnit)
        {
            CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Hero_Sell, gridUnit.Display.transform);
        }

        public void ShotFootPrintEffect(ACGrid gridUnit)
        {
            if(gridUnit.GridType == GridType.PreChooseGrid)
                CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Hero_Footprint, gridUnit.Display.transform);
            else
                CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_150_zizouqi_changjingyanwu, gridUnit.Display.transform);
        }

        /// <summary>
        /// 飞星的UI特效
        /// </summary>
        public void ShotFireFlyEffect(RectTransform root, RectTransform end, int acGroupId)
        {
            GameMain.Instance.StartCoroutine(FlyBoom(root, end, acGroupId));
            AudioTool.Instance.LoadAndPlayAudioEffect("AC_buffActive");
        }

        IEnumerator FlyBoom(RectTransform root, RectTransform end, int acGroupId)
        {
            yield return null;

            Vector2 screenPos = CameraTools.Instance._uiCamera.WorldToScreenPoint(end.position);
            Vector2 localPos = Vector2.zero;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(root, screenPos, CameraTools.Instance._uiCamera, out localPos);
            Vector3 endPos = new Vector3(localPos.x, localPos.y, 0);

            var allHeros = AutoChessPlayerCtr.Ins.CurrentPlayer.HeroUnits;
            for (int i = 0; i < allHeros.Count; i++)
            {
                var unit = allHeros[i];
                var tableHero = Table.Blo.AutoChessBlo.GetChessHero(unit.HeroID);
                var groups = tableHero.acHeroGroups.Split(';');
                if (unit.MapGrid.GridType != GridType.FightGrid)
                    continue;

                for (int j = 0; j < groups.Length; j++)
                {
                    if (int.Parse(groups[j]) == acGroupId)
                    {
                        screenPos = AutoChessCamera.Ins.acCamera.WorldToScreenPoint(unit.Display.transform.position);
                        localPos = Vector2.zero;
                        RectTransformUtility.ScreenPointToLocalPointInRectangle(root, screenPos, CameraTools.Instance._uiCamera, out localPos);
                        Vector3 startPos = new Vector3(localPos.x, localPos.y, 0);
                        MeteorEffect.GenMeteorEffect(root, startPos, endPos);
                        
                        break;
                    }
                }
            }

            yield return new WaitForSeconds(0.5f);

            CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.UI_150_zizhouqi_bao, end);
        }

        public void PlayHeroSetSound(int heroId)
        {
            if (cacheData.ServerDataState == AutoChessStateType.AUTO_CHESS_STATE_FIGHTING)
                return;

            var tableModel = Table.Blo.TableSailorModelBlo.GetTableSailorModelByHeroIdAndAppearence(heroId);
            var heroSounds = Table.Blo.TableHeroSceneActionBlo.GetFormationActions(tableModel.ModelId);
            if(heroSounds.Count > 0)
            {
                var i = UnityEngine.Random.Range(0, heroSounds.Count - 1);
                AudioTool.Instance.StopEffectMusic();
                AudioTool.Instance.LoadAndPlayAudioEffect(heroSounds[i].sound);
            }
        }
    }
}
